package org.dreamwork.cai.io.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.dreamwork.cai.internal.pojo.JsonInvocationPayload;
import org.dreamwork.cai.internal.pojo.JsonInvocationResult;
import org.dreamwork.cai.proxy.IServiceResolver;
import org.dreamwork.cai.proxy.ProxyInvoker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServiceProviderAdapter extends SimpleChannelInboundHandler<JsonInvocationPayload> {
    private final Logger logger = LoggerFactory.getLogger (ServiceProviderAdapter.class);
    private final IServiceResolver resolver;

    public ServiceProviderAdapter (IServiceResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    protected void channelRead0 (ChannelHandlerContext ctx, JsonInvocationPayload payload) {
        System.out.println (payload);

        JsonInvocationResult jir = ProxyInvoker.invoke (resolver, payload);
/*
        if (jir == null) {
            logger.warn ("can't find requested service: {}/{}/{}", payload.namespace, payload.name, payload.uuid);
            jir = new JsonInvocationResult ();
            jir.code = 404;
            jir.error = "Service Not Available";
        }
*/
        ctx.writeAndFlush (jir);
    }
}